package sw.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import sw.entity.Books;
import sw.entity.Classes;
import sw.repo.BooksRepository;
import sw.repo.ClassesRepository;

@Controller
public class allController {
	
	@Autowired
	private BooksRepository booksRepo;
	
	@Autowired
	private ClassesRepository clasRepo;
	
     @GetMapping("/")
     public String showHome(Model model){
    	 Iterable<Books> books = booksRepo.findAll();
    	 model.addAttribute("books", books);
    	 return "/home";
     }
     @GetMapping("/hou")
     public String showHouHome(Model model){
    	 Iterable<Books> books = booksRepo.findAll();
    	 model.addAttribute("books", books);
    	 return "/index";
     }
     
     @GetMapping("/addBooks")
     public String addBooksShow(Model model){
    	 
    	 model.addAttribute("classes", clasRepo.findAll());
    	 return "/addBooks";
     }
     
     @GetMapping("/booksList")
     public String booksShowList(Model model){
    	 Iterable<Books> books = booksRepo.findAll();
    	 model.addAttribute("books", books);
    	 return "/booksList";
     }
     
     @PostMapping("/addBookFun")
     public String addBook(Books book,Long classesId){
    	 Classes classes = clasRepo.findOne(classesId);
//			Classes classes =new Classes();
//			classes.setId(classesId);
//
			//把班级对象联系上了一个学院对象
		book.setClasses(classes);
  
    	 booksRepo.save(book);
    	 return "redirect:/hou";
     }
     
     
     @GetMapping("/del/{id}")
     public String deleteBook(@PathVariable Long id){
    	 booksRepo.delete(id);
    	 return "redirect:/hou";
     }
     @GetMapping("/see/{id}")
     public String seeBook(@PathVariable Long id,Model model){
    	 Books book=booksRepo.findOne(id);
    	 model.addAttribute("book", book);
    	 return "/see";
     }
     
     //修改
     @GetMapping("/change/{id}")
     public String change(@PathVariable Long id,Model model){
    	 Books book = booksRepo.findOne(id);
    	 model.addAttribute("book", book);
    	 model.addAttribute("classes", clasRepo.findAll());
    	 return "/changeBooks";
     }
     @PostMapping("/changePost/{id}")
     public String changePost(@PathVariable Long id,Books bb,Long classesId){
    	 Books book = new Books();
    	 book.setId(id);
    	 book.setName(bb.getName());
    	 book.setAuthor(bb.getAuthor());
    	 book.setPressName(bb.getPressName());
    	 book.setDate(bb.getDate());
    	 book.setDecri(bb.getDecri());
    	 Classes classes = clasRepo.findOne(classesId);
    	 book.setClasses(classes);
    	 booksRepo.save(book);
    	 
    	 
    	 return "redirect:/hou";
     }
     
}
